package com.system.presideover.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.system.common.result.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

@RestController
@CrossOrigin(origins = "*")
@Api(tags = "下载图片")
@RequestMapping("/presideover/common")
public class ImageController {

    @Value("${imageUrl}")
    private String basePath;

    @Value("${urlVideo}")
    private String urlVideo;

    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;


    @Value("${aliyun.oss.file.accessKeyId}")
    private String accessKeyId;


    @Value("${aliyun.oss.file.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketname;

//    public static void uploadFile(String fileName,String saveFileName) throws FileNotFoundException {
//        // 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        // 上传文件流。
//        InputStream inputStream = new FileInputStream(fileName);
//        ossClient.putObject(bucketName, saveFileName, inputStream);
//        // 关闭OSSClient。
//        ossClient.shutdown();
//    }



    /**
     * 文件上传
     * @param file
     * @return
     */
//    @PostMapping("/upload")
//    public Result upload(MultipartFile file) {
//        //获取文件名
//        String originalFilename = file.getOriginalFilename();
//        //获取文件格式
//        String subFile= originalFilename.substring(originalFilename.lastIndexOf("."));
//        //生成随机的文件名字
//        String filename = UUID.randomUUID().toString() + subFile;
//        File file1 = new File(basePath);
//
//        //TODO  对接oss
//        //判断存放图片的目录是否存在，不存在则进行创建
//        if (!file1.exists()) {
//            file1.mkdirs();
//        }
//
//
//        try {
//            //错误示范
////            file.transferTo(new File(file1 + filename));
//            //将临时文件转存到指定位置
//            file.transferTo(new File(basePath + filename));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return Result.ok(filename);
//    }

    /**
     * oss上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件名
        String originalFilename = file.getOriginalFilename();

//        //JDK8的日期格式
//        LocalDateTime time = LocalDateTime.now();
//        DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy/MM/dd");
//
//        //拼装OSS上存储的路径
//        String folder = dft.format(time);
        String fileName = generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = fileName + extension;

        //在OSS上bucket下的文件名
        String uploadFileName = "picture/" + fileName + extension;


        try {

            PutObjectResult result = ossClient.putObject(bucketname, uploadFileName,file.getInputStream());
            if (result != null) {
//                String name = "https://"+bucketname+"."+extension+"/"+uploadFileName;
                String name = "https://missok12.oss-cn-beijing.aliyuncs.com/"+uploadFileName;
                return Result.ok(name).message("上传成功");
            }
        } catch (IOException io) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + io.getMessage());
            return Result.fail().message("文件上传失败:{}");
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return Result.fail().message("文件上传失败:{}");
    }

    /**
     * 获取随机字符串
     * @return
     */
    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
//    @GetMapping("/download")
//    public void download(String name, HttpServletResponse response) {
//
//        //TODO  对接oss下载回显
//
//        try {
//            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
//            //输出流，通过输出流将文件写回浏览器
//            ServletOutputStream outputStream = response.getOutputStream();
//
//            response.setContentType("image/jpeg");
//            response.setContentType("video/mp4");
//            int len = 0;
////            byte[] bytes = new byte[1024];
//            byte[] bytes = new byte[4096];
//            while ((len = fileInputStream.read(bytes)) != -1){
//                outputStream.write(bytes,0,len);
//                outputStream.flush();
//            }
//
//            outputStream.close();
//            fileInputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//
//    }


    /**
     * oss实现下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        //TODO  对接oss下载回显

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            String objectKey = "picture/" + name;

        try {
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元数据。
            OSSObject ossObject = ossClient.getObject(bucketname, objectKey);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            InputStream content = ossObject.getObjectContent();
            if (content != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    System.out.println("\n" + line);
                }
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                content.close();
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException io) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + io.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

//        try {
//            // 创建获取文件的请求
//            String objectKey = "picture/";
//            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketname, objectKey);
//
//            // 通过OSSClient对象执行获取文件的请求，返回OSSObject对象
//            OSSObject ossObject = ossClient.getObject(getObjectRequest);
//
//            // 获取OSSObject对象的内容流
//            InputStream inputStream = ossObject.getObjectContent();
//
//            response.setContentType("image/jpeg");
//            response.setContentType("video/mp4");
//
//            // 创建本地文件输出流
//            FileOutputStream fileOutputStream = new FileOutputStream(new File(name));
//
//            // 将OSSObject对象的内容流写入本地文件
////            byte[] buffer = new byte[4096];
////            byte[] buffer = new byte[8192];
//            byte[] buffer = new byte[16384];
//            int len;
//            while ((len = inputStream.read(buffer)) != -1) {
//                fileOutputStream.write(buffer, 0, len);
//            }
//            // 关闭流
//            fileOutputStream.close();
//            inputStream.close();
//
//            System.out.println("文件下载成功！");
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            // 关闭OSSClient
//            ossClient.shutdown();
//        }


    }

//    @PostMapping("/load")
//    public List<Object> uploadImages(@RequestParam("files") MultipartFile[] files) {
//        List<String> fileUrls = new ArrayList<>();
//
//        String filename = null;
//        for (MultipartFile file : files) {
//            // 获取文件名
//            String fileName = file.getOriginalFilename();
//
//            // 保存文件到服务器指定目录
//            // ...
//            //获取文件格式
//            String subFile = fileName.substring(fileName.lastIndexOf("."));
//            //生成随机的文件名字
//            filename = UUID.randomUUID().toString() + subFile;
//            File file1 = new File(basePath);
//            //判断存放图片的目录是否存在，不存在则进行创建
//            if (!file1.exists()) {
//                file1.mkdirs();
//            }
//
//
//            try {
//                //错误示范
////            file.transferTo(new File(file1 + filename));
//                //将临时文件转存到指定位置
//                file.transferTo(new File(basePath + filename));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//            // 构造文件URL
////            String fileUrl = basePath + fileName;
//            fileUrls.add(filename);
//
//        }
//        for (String fileUrl : fileUrls) {
//
////            String substring = fileUrl.substring(fileUrl.lastIndexOf(","));
//            return (List<Object>) Result.ok(fileUrl);
//        }
//        return Result.fail();
//
//    }

//    @ApiOperation("上传多张图片")
//    @PostMapping(value = "/listImages")
//    // 创建一个DiskFileItemFactory对象，设置内存阀值为10KB
//            public Result listImages(){
//    DiskFileItemFactory factory = new DiskFileItemFactory();
//
//    // 设置最大内存限制为2MB
//      factory.setSizeThreshold(2 * 1024 * 1024);
//
//    // 获取ServletContext对象
////    ServletContext servletContext = getServletConfig().getServletContext();
//        ServletConfig servletConfig = new ServletConfig() {
//            @Override
//            public String getServletName() {
//                return null;
//            }
//
//            @Override
//            public ServletContext getServletContext() {
//                return null;
//            }
//
//            @Override
//            public String getInitParameter(String name) {
//                return null;
//            }
//
//            @Override
//            public Enumeration<String> getInitParameterNames() {
//                return null;
//            }
//        }
//    ServletContext servletContext = servletConfig().get.getServletContext();
//
//    // 指定保存路径
//    String savePath = servletContext.getRealPath("/images");
//
//    // 将工厂与保存路径关联起来
//      factory.setRepository(new File(savePath));
//
//    // 创建一个新的文件上传处理器
//    ServletFileUpload upload = new ServletFileUpload(factory);
//
//      try {
//        // 解析HTTP POST请求
//        List items = upload.parseRequest(request);
//
//        for (Iterator iter = items.iterator(); iter.hasNext(); ) {
//            FileItem item = (FileItem) iter.next();
//
//            if (!item.isFormField()) {
//                // 判断当前表单字段是否为文件类型
//
//                // 获取原始文件名
//                String fileName = item.getName();
//
//                // 构造保存到服务器的完整路径
//                String fileSavePath = savePath + "/" + fileName;
//
//                // 保存文件到服务器
//                item.write(new File(fileSavePath));
//
//                System.out.println("文件 " + fileName + " 已成功上传到 " + fileSavePath);
//            } else {
//                // 其他非文件类型的表单字段处理...
//            }
//        }
//    } catch (Exception e) {
//        throw new RuntimeException("文件上传失败", e);
//    }
//      return Result.ok();
//}

    /**
     * oss实现下载
     * @param name
     * @param response
     */
    @PostMapping("/delectPrcture")
    public void delectprcture(String name, HttpServletResponse response) {

        //TODO  对接oss下载回显

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String subFile = name.substring(name.lastIndexOf("picture/"));
//        String str = name.substring(name.lastIndexOf("/"));
//        String[] parts = str.split("/");
//        String s_without_slash = parts.length > 0 ? parts[1] : "";

        try {
            // 删除文件。
            ossClient.deleteObject(bucketname, subFile);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
